package cn.tmpan.controller.publics;

import cn.tmpan.common.ServerResponse;
import cn.tmpan.service.IFileService;
import cn.tmpan.util.PropertiesUtil;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 文件长传 选择是否上传到ftp服务器
 */
@Controller
@RequestMapping("/File/")
public class FileController {

    @Autowired
    private IFileService iFileService;

    @RequestMapping(value = "upload",method = RequestMethod.POST)
    @ResponseBody
    /**
     * 上传文件到服务器
     */
    public ServerResponse upload(HttpServletRequest request, @RequestParam(value = "upload_file", required = false) MultipartFile multipartFile) {

        //是否上传到FTP服务器
        boolean isServer=true;

        //获取项目路径
        String path = request.getSession().getServletContext().getRealPath("upload");
        //获取上传成功后的文件名
        String targetName = iFileService.uploadFile(multipartFile, path,isServer);

        //设置图片网络访问地址
        String url = PropertiesUtil.getProperty("ftp.server.http.prefix") +"images/"+ targetName;


        //封装数据对象
        Map fileMap = Maps.newHashMap();
        fileMap.put("uri", targetName);
        fileMap.put("url", url);
        //返回结果
        return ServerResponse.createBySuccessData(fileMap);

    }

}
